<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>球类游戏</title>
    <style>
        body {
            margin: 0;
            font-family: 'Arial', sans-serif;
            background: #f0f0f0;
        }

        .container {
            height: 100vh;
            width: 100vw;
            overflow-x: hidden;
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .ball {
            width: 100px;
            height: 100px;
            background: #cccc00;
            border-radius: 50%;
            margin: 0 10px;
            transition: opacity 0.3s ease-in-out;
            cursor: pointer;
        }

        .score {
            position: absolute;
            top: 10%;
            left: 50%;
            transform: translateX(-50%);
            padding: 20px 40px;
            background: linear-gradient(135deg, #ff7b00, #ff4c00);
            color: white;
            border-radius: 15px;
            font-size: 2em;
            font-weight: bold;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            text-align: center;
        }

        .start-button, .restart-button {
            padding: 15px 30px;
            background: #ff7b00;
            color: white;
            font-size: 1.5em;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            bottom: 20%;
            transform: translate(-50%,-400%);
            transition: background-color 0.3s ease;
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-left: 50%;
            margin-bottom: 10%;
        }

        .start-button:hover{
            background-color: #ff4c00;
        }

        .floating-text {
            position: absolute;
            font-size: 2em;
            font-weight: bold;
            opacity: 0;
            animation: floatText 3s ease-out forwards;
            white-space: nowrap;
            left: 50%;
            transform: translateX(-50%);
        }

        @keyframes floatText {
            0% { transform: translateX(-100%); opacity: 0; }
            50% { transform: translateX(-50%); opacity: 1; }
            100% { transform: translateX(0%); opacity: 0; }
        }

        .timer {
            position: absolute;
            top: 10%;
            right: 10%;
            font-size: 2em;
            color: red;
            font-weight: bold;
        }

        .floating-text-container {
            position: absolute;
            top: 25%;
            width: 100%;
            overflow: visible;
        }

        .feedback-text {
            position: absolute;
            font-size: 2em;
            font-weight: bold;
            opacity: 0;
            animation: feedbackAnim 1s ease-out;
            white-space: nowrap;
            left: 50%;
            transform: translateX(-50%);
        }

        @keyframes feedbackAnim {
            0% { transform: translate(-50%, 0); opacity: 1; }
            100% { transform: translate(-50%, -100px); opacity: 0; }
        }
        .perfect { color: #ffd700; font-size: 2.5em; text-shadow: 0 0 10px rgba(255, 215, 0, 0.5); }
        .good { color: #00ff00; }
        .error { color: #ff0000; }
        .leaderboard {
            position: absolute;
            top: 20%;
            right: 2%;
            background: linear-gradient(135deg, #ff7b00, #ff4c00);
            border-radius: 15px;
            padding: 20px;
            width: 300px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
            color: white;
            text-align: center;
        }

        .leaderboard h2 {
            margin: 0 0 20px;
            font-size: 1.8em;
            color: white;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
        }

        .leaderboard ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .leaderboard li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            margin-bottom: 10px;
            background-color: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
            transition: background-color 0.3s ease;
        }

        .leaderboard li:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }

        .leaderboard li span:nth-child(1) {
            font-weight: bold;
            font-size: 1.2em;
        }

        .leaderboard li span:nth-child(2) {
            font-size: 1.2em;
        }
    </style>
</head>
<body>
<div class="container">
    <div id="ball1" class="ball"></div>
    <div id="ball2" class="ball"></div>
    <div id="ball3" class="ball"></div>
    <div id="ball4" class="ball"></div>
    <div id="ball5" class="ball"></div>
</div>
<div class="score" id="score">得分: 0</div>
<button class="start-button" id="startButton">开始游戏</button>
<div class="timer" id="timer">剩余时间: 60</div>


<div class="leaderboard">
    <h2>排行榜</h2>
    <ul id="leaderboardList"></ul>
</div>

<script>
    // 游戏变量
    let score = 0;
    let gameStarted = false;
    let timer;
    let floatingTextTimer;
    let gameTime = 60; // 游戏限时 60 秒
    let remainingTime = gameTime;
    let currentColorIndex = -1;
    let targetStartTime = 0; // 目标颜色出现的时间
    let isClicked = false; // 新增：记录当前目标颜色是否已被点击

    // 获取页面元素
    const balls = document.querySelectorAll('.ball');
    const colors = ['#FF0000', '#FF8C00', '#CCCC00', '#0000FF', '#00FF00'];
    const scoreElement = document.getElementById('score');
    const startButton = document.getElementById('startButton');
    const timerElement = document.getElementById('timer');
    const floatingTextContainer = document.createElement('div');//创建一个元素
    floatingTextContainer.classList.add('floating-text-container');//添加一个css样式
    document.body.appendChild(floatingTextContainer);//把div插入到body

    // 排行榜相关
    const leaderboardList = document.getElementById('leaderboardList');
    const leaderboard = JSON.parse(localStorage.getItem('leaderboard')) || [];

    // 颜色对应的文本
    const colorNames = ['红', '橙', '黄', '蓝', '绿'];

    // 显示反馈文字
    const showFeedbackText = (text, className) => {
        const feedback = document.createElement('div');
        feedback.classList.add('feedback-text', className);
        feedback.innerText = text;
        floatingTextContainer.appendChild(feedback);

        setTimeout(() => {
            feedback.remove();
        }, 1000); // 反馈文字展示 1 秒后移除
    };

    // 点击球时的处理函数
    function onclick(event) {
        if (!gameStarted || isClicked) return;

        const { id } = event.target;
        const reg = /^ball(\d)$/;
        const result = id.match(reg);
        const num = result[1] - 1;

        const clickTime = Date.now();
        const reactionTime = (clickTime - targetStartTime) / 1000;

        if (num === currentColorIndex) {
            isClicked = true;
            if (reactionTime <= 1.0) {
                showFeedbackText('Perfect!', 'perfect');
                score += 15;
            } else if (reactionTime <= 1.5) {
                showFeedbackText('Good!', 'good');
                score += 10;
            } else {
                showFeedbackText('Good!', 'good');
                score += 5;
            }
        } else {
            isClicked = true;
            showFeedbackText('Error!', 'error');
            score -= 5;
        }

        scoreElement.innerText = `得分: ${score}`;
        event.target.style.opacity = 0;
        setTimeout(() => {
            event.target.style.opacity = 1;
        }, 300);
    }

    // 开始游戏
    function startGame() {
        gameStarted = true;
        score = 0;
        scoreElement.innerText = `得分: ${score}`;
        startButton.style.display = 'none';

        // 绑定点击事件
        balls.forEach((ball) => {
            ball.addEventListener('click', onclick);
        });

        remainingTime = gameTime;
        timerElement.innerText = `剩余时间: ${remainingTime}`;
        timer = setInterval(() => {
            remainingTime--;
            timerElement.innerText = `剩余时间: ${remainingTime}`;
            if (remainingTime <= 0) {
                clearInterval(timer);
                clearInterval(floatingTextTimer);
                endGame();
            }
        }, 1000);

        floatingTextTimer = setInterval(() => {
            currentColorIndex = Math.floor(Math.random() * colors.length);
            targetStartTime = Date.now();
            isClicked = false;
            showFloatingText();
        }, 1500);
    }

    // 游戏结束
    function endGame() {
        gameStarted = false;
        startButton.style.display = 'block';

        const username = prompt('请输入您的用户名:');
        if (username) {
            leaderboard.push({ name: username, score });
            leaderboard.sort((a, b) => b.score - a.score);
            localStorage.setItem('leaderboard', JSON.stringify(leaderboard));
            updateLeaderboard();
        }
    }

    // 更新排行榜
    function updateLeaderboard() {
        leaderboardList.innerHTML = '';
        leaderboard.forEach((entry, index) => {
            const li = document.createElement('li');
            li.innerHTML = `<span>${index + 1}. ${entry.name}</span><span>${entry.score} 分</span>`;
            leaderboardList.appendChild(li);
        });
    }

    // 初始化排行榜
    updateLeaderboard();

    // 重置游戏状态
    function resetGameState() {
        clearInterval(timer);
        clearInterval(floatingTextTimer);
        gameStarted = false;
        remainingTime = gameTime;
        currentColorIndex = -1;
        isClicked = false;
        clearFloatingText();
    }

    // 设置每个球的颜色
    balls.forEach((ball, index) => {
        ball.style.background = colors[index];
    });

    // 显示漂浮文字
    const showFloatingText = () => {
        clearFloatingText();

        const text = document.createElement('div');
        text.classList.add('floating-text');
        text.style.color = colors[currentColorIndex];
        text.innerText = `点击: ${colorNames[currentColorIndex]} 球`;
        floatingTextContainer.appendChild(text);

        setTimeout(() => {
            text.remove();
        }, 3000);
    };

    // 清除漂浮文字
    const clearFloatingText = () => {
        while (floatingTextContainer.firstChild) {
            floatingTextContainer.firstChild.remove();
        }
    };//循环删除容器里的子节点，保证每个球只能点击一次

    // 绑定按钮事件
    startButton.addEventListener('click', startGame);

</script>
</body>
</html>